from datetime import date

from rest_framework.response import Response
from rest_framework.views import APIView

from apps.goods.models import GoodsVisitCount

from apps.orders.models import OrderInfo
from apps.users.models import User
from rest_framework.permissions import IsAdminUser
from rest_framework.generics import ListAPIView

#统计用户总数
class TotalView(APIView):
    permission_classes = [IsAdminUser]  #权限验证
    def get(self,request):
        #统计用户总数
        total = User.objects.filter(is_staff=False).count()
        return Response({
            'count':total,
            'date':date.today()
        })

#统计今天新增用户数量
class DayAddView(APIView):
    permission_classes = [IsAdminUser]  #权限验证
    def get(self,request):
        today = date.today()   #没有时分秒
                                            #注册时间大于时间0分0秒 就表示新增的
        total = User.objects.filter(is_staff=False,date_joined__gte=today)
        return Response({
            'count': total,
            'date': date.today()
        })
#日活跃用户
class ActiveView(APIView):
    permission_classes = [IsAdminUser]  #权限验证  管理员权限
    def get(self,request):
        # 统计用户总数

        today = date.today()  # 没有时分秒
        total = User.objects.filter(is_staff=False,last_login__gte=today).count()
        return Response({
            'count': total,
            'date': date.today()
        })
#日下单用户统计
class OrderView(APIView):
    permission_classes = [IsAdminUser]

    def get(self,request):
        # DISTINCT ON fields is not supported by this database backend'数据库后端不支持
###如果想用distinct的话，在distinct前面加上values或values_list
        count = OrderInfo.objects.filter(create_time__gte=date.today()).values_list('user_id').distinct().count()

        #去掉一天之内的一个用户下了多个订单
        #一个用户 对应多个订单 1：多  多对象的纯小写  orderinfo
        # count = User.objects.filter(orderinfo__create_time__gte=date.today()).distinct().count()

        return Response({
            'count': count,
            'date': date.today()
        })
#月增用户统计
class MonthAddView(APIView):
    permission_classes = [IsAdminUser]

    def get(self,request):
        from datetime import timedelta   #可以做时间差
        count_list = []

        for i in range(30,0,-1):
            date_begin = date.today()-timedelta(days=i)
            date_end = date_begin + timedelta(days=1)

            count = User.objects.filter(is_staff=False,date_joined__gte=date_begin,date_joined__lt=date_end).count()
            count_list.append({
            'count': count,
            'date': date_begin
            })
        return Response(count_list)

#日分类商品访问量
from apps.meiduo_admin.serializers.statistical import GoodsSerializer
class GoodsView(ListAPIView):
    permission_classes = [IsAdminUser]
    #查询所有的三级访问量
    queryset = GoodsVisitCount.objects.filter(date = date.today())
    serializer_class = GoodsSerializer  #通过序列化器将访问量转成字典